<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import wsjzglService from '@/api/wsjzgl'
import { getFldm } from '@/utils/get-fldm'
import type { FormInstance, FormRules } from 'element-plus'
import { useMainStore } from '@/store/main'
import { useRoute } from 'vue-router'
const route = useRoute()
const store = useMainStore()
const emit = defineEmits(['refresh'])

const isLoading = ref(false)
const isSaveLoading = ref(false)
// 生命周期
onMounted(() => {
  // 查询责任者（单位树）
  queryDwTree()
})

/*
 * 获取密级（分类代码）
 */
const mjList = ref<any[]>([])
const getMj = async () => {
  mjList.value = await getFldm('gd006')
}

/*
 * 查询责任者（单位树）
 */
const queryDwTree = () => {
  //
}

/* 弹框状态 */
const dialogVisible = ref(false)

/* 获取节点信息 */
const nodeData = ref<any>([])
/*
 * 打开弹框
 */

const openDialog = async (e: any) => {
  nodeData.value = e
  await getMj()
  ruleForm.value.mjdm = mjList.value[0]?.dm
  ruleForm.value.mjmc = mjList.value[0]?.mc
  ruleForm.value.zrz = store.userInfo.dwmc
  dialogVisible.value = true
}

/*
 * 关闭弹框
 */
const closeDialog = () => {
  nextTick(() => {
    ruleFormRef.value?.resetFields()
  })
  dialogVisible.value = false
}

/*
 * 保存（成功抛出刷新）
 */
const save = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      const params = {
        ...ruleForm.value,
        ajbh: nodeData.value.ajbh,
        mlsxh: (nodeData.value.cj === '2' && nodeData.value.mlsxh) || '0',
      }
      isSaveLoading.value = true
      wsjzglService
        .saveAjml(params, route.query.ajbh as string)
        .then(() => {
          ElMessage({
            type: 'success',
            message: '保存成功',
          })
          emit('refresh', nodeData.value.ajbh)
          closeDialog()
        })
        .catch((err) => {
          !err.isError && ElMessage({ type: 'warning', message: err.message })
        })
        .finally(() => {
          isSaveLoading.value = false
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}
/*
 * 保存并添加（成功抛出刷新）
 */
const saveAdd = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      const params = {
        ...ruleForm.value,
        ajbh: nodeData.value.ajbh,
        mlsxh: (nodeData.value.cj === '2' && nodeData.value.mlsxh) || '0',
      }
      isLoading.value = true
      wsjzglService
        .saveAjml(params, route.query.ajbh as string)
        .then(() => {
          ElMessage({
            type: 'success',
            message: '保存成功',
          })
          nextTick(() => {
            ruleFormRef.value?.resetFields()
          })
          emit('refresh', nodeData.value.ajbh)
        })
        .catch((err) => {
          !err.isError && ElMessage({ type: 'warning', message: err.message })
        })
        .finally(() => {
          isLoading.value = false
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref({
  mlmc: '',
  wh: '',
  zrz: '',
  mlscrq: '',
  mjdm: '',
  mjmc: '',
  zwys: undefined,
  qfys: undefined,
  dgys: undefined,
  bz: '',
})
/* 表单校验 */
const rules = ref<FormRules>({
  mlmc: [
    {
      required: true,
      message: '请输入题名',
      trigger: 'change',
    },
  ],
  zrz: [
    {
      required: true,
      message: '请输入责任者',
      trigger: 'change',
    },
  ],
  mlscrq: [
    {
      required: true,
      message: '请选择日期',
      trigger: 'change',
    },
  ],
  mjdm: [
    {
      required: true,
      message: '请选择密级',
      trigger: 'change',
    },
  ],
  zwys: [
    {
      required: true,
      message: '请输入正文页数',
      trigger: 'change',
    },
  ],
})

// 密级change事件
const mjChange = (dm: string) => {
  const mj = mjList.value.find((mj) => mj.dm === dm)
  ruleForm.value.mjmc = mj.mc
}

defineExpose({
  openDialog,
})
</script>
<template>
  <!-- 添加目录弹窗 -->
  <el-dialog
    v-model="dialogVisible"
    title="添加目录"
    width="50%"
    :close-on-click-modal="false"
    :before-close="closeDialog"
  >
    <el-form ref="ruleFormRef" label-width="auto" :model="ruleForm" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="题名" prop="mlmc">
            <el-input
              v-model="ruleForm.mlmc"
              maxlength="30"
              placeholder="请输入题名"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="文号" prop="wh">
            <el-input v-model="ruleForm.wh" maxlength="100" placeholder="请输入文号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="责任者" prop="zrz">
            <el-input v-model="ruleForm.zrz" maxlength="50" placeholder="请输入责任者" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="日期" prop="mlscrq" style="width: 100%">
            <el-date-picker
              style="width: 100%"
              v-model="ruleForm.mlscrq"
              type="date"
              placeholder="请选择"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="密级" prop="mjdm">
            <el-select v-model="ruleForm.mjdm" placeholder="请选择" @change="mjChange">
              <el-option
                v-for="item in mjList"
                :key="item.dm"
                :label="item.mc"
                :value="item.dm"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="正文页数" prop="zwys">
            <el-input-number
              style="width: 100%"
              v-model="ruleForm.zwys"
              :controls="false"
              :min="0"
              :max="100000000"
              placeholder="请输入正文页数"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签发页数" prop="qfys">
            <el-input-number
              style="width: 100%"
              v-model="ruleForm.qfys"
              :controls="false"
              :min="0"
              :max="100000000"
              placeholder="请输入签发页数"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="底稿页数" prop="dgys">
            <el-input-number
              style="width: 100%"
              v-model="ruleForm.dgys"
              :controls="false"
              :min="0"
              :max="100000000"
              placeholder="请输入底稿页数"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="bz">
            <el-input v-model="ruleForm.bz" maxlength="200" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="save(ruleFormRef)" :loading="isSaveLoading"
          >保存</el-button
        >
        <el-button type="primary" @click="saveAdd(ruleFormRef)" :loading="isLoading"
          >保存并添加</el-button
        >
        <el-button @click="closeDialog">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
:deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
